package jplat.tools.config;

import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import jplat.tools.string.StringUtil;
import jplat.tools.string.XLog;

public class JBasePropertiesReader
{
	//待替换成Properties.
	private List<ResourceBundle> confList;
	
	public JBasePropertiesReader( String ...proName )
	{
		confList = new ArrayList<ResourceBundle>();
		for ( String confpath : proName )
		{
			confList.add(ResourceBundle.getBundle(confpath));
		}
	}

	public String getString(String key, boolean must )
	{
		XLog.log("find value for key:"+key);
		for ( int i = 0; i < confList.size(); ++i )
		{
			try
			{
				String value = confList.get(i).getString(key);
				return value==null?"":value.trim();
			}
			catch (MissingResourceException e)
			{
				continue;
			}
		}
		
//		XLog.log("__LOAD:key property[%s] not found.", key);
		if ( must )
		{
			throw new RuntimeException( "key property [" + key + "] not found" );
		}
		
		return "";
	}
	
	public String getString(String key )
	{
		return getString( key, false );
	}
	
	public String getString(String key, String defval )
	{
		String retVal = getString(key,false);
		if ( StringUtil.isEmpty(retVal) )
		{
			return defval;
		}
		
		return retVal;
	}
	
	public int getInt(String key)
	{
		String cf = getString(key,false);
		if ( StringUtil.isEmpty(cf) )
		{
			return 0;
		}
		
		return Integer.parseInt(cf);
	}
	
	public int getInt(String key, boolean must )
	{
		return Integer.parseInt(getString(key,must));
	}
	
	public int getInt(String key,int defval )
	{
		int retval = getInt(key);
		if (retval==0)
		{
			return defval;
		}
		
		return retval;
	}
	
	public boolean getBoolean(String key)
	{
		String value = getString(key,false);
		if ( value != null )
		{
			value = value.trim();
		}
		
		return "true".equalsIgnoreCase(value);
	}
	
	public static void main( String args[] )
	{
		XLog.log(new JBasePropertiesReader("conf/service/service-mapper").getString("PAPE0001",true));
	}
}